<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>新建半成品</title> 

    <link type="text/css" href="/TopJUI/topjui/css/topjui.core.min.css" rel="stylesheet">
    <link type="text/css" href="/TopJUI/topjui/themes/default/topjui.green.css" rel="stylesheet" id="dynamicTheme"/>
    <!-- FontAwesome字体图标 -->
    <link type="text/css" href="/TopJUI/topjui/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
    <link rel="stylesheet" type="text/css" href="/pages/css/process.css">    
    <!-- buttons 组件 -->
    <link type="text/css" href="/buttons/buttons.css" rel="stylesheet"/>    
    <!-- jQuery相关引用 -->
    <script type="text/javascript" src="/TopJUI/topjui/plugins/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/TopJUI/topjui/plugins/jquery/jquery.cookie.js"></script>
    <!-- TopJUI框架配置 -->
    <script type="text/javascript" src="/TopJUI/static/public/js/topjui.config.js"></script>
    <!-- TopJUI框架核心-->
    <script type="text/javascript" src="/TopJUI/topjui/js/topjui.core.min.js"></script>
    <!-- TopJUI中文支持 -->
    <script type="text/javascript" src="/TopJUI/topjui/js/locale/topjui.lang.zh_CN.js"></script>

    <script type="text/javascript" src="/pages/js/moment.min.js"></script>
    <script type="text/javascript" src="/pages/js/layer/layer.js"></script>
    <script type="text/javascript" src="/pages/js/util.js"></script>
    <script type="text/javascript" src="/pages/js/shuoheUtil.js"></script>

    <script type="text/javascript" src="/pages/js/vue.js"></script>
    <script type="text/javascript" src="/pages/js/Sortable.min.js"></script>
    <script type="text/javascript" src="/pages/js/vuedraggable.min.js"></script>
    
<style type="text/css">
    html, body{ margin:0; height:100%;width: 100%;border-width:0px}
    .compute-list li{
        float: left;
        padding: 3px 5px;
        margin: 0 15px;
        list-style: none;
        border: 1px solid #dddddd;
        cursor: move;
    }
    .dragCon{
        min-height: 100px;
        padding: 10px 10px;
        border: 1px solid #dddddd;
    }
    .drag-li{
        padding: 0 8px;
        position: relative;
    }
    .drag-li a{
        position: absolute;
        top: 0;
        right: 0;
        font-size: 12px;
        color: #333;
        text-decoration: none;
        display: none;
    }
    .drag-li:hover a{
        display: block;
    }
    .build-btn{
        height: 32px;
        line-height: 32px;
        border: none;
        background-color: #2e8ded;
        color: #fff;
        padding: 0 8px;
        cursor: pointer;
    }
    .const-input{
        width: 60px;
        height: 24px;
        line-height: 24px;
    }    
</style>


<body class="easyui-layout">
    <div data-options="region:'west',iconCls:'icon-reload',title:'',split:false,border:true" 
         style="height:60px;width: 100%;height: 45px;border-width:0px;overflow:hidden" >  
	    <table class="editTable" style="text-align: center; margin-top: 0px;margin-left:0px" >
	        <tr>
	            <td class="label">名称</td>
	            <td >
	                <input id='pc_pid' class="easyui-textbox" data-options="required:false,width:150,editable:true" >
	            </td>
	            <td class="label">装备模式</td>
	            <td >
                    <select id='partsName' class="easyui-combobox" data-options="required:false,width:150,editable:true"  >     
                        <option>全选</option>  
                        <option>单选</option>         
                        <option>多选</option>  
                    </select> 
	            </td>
            </tr>	
            <tr class="gs"> 
                <td class="label">公式输入</td>
                <td colspan="3" style="text-align: left;">
                    <input type="hidden" id="designJson">
                    <input id='design_formulas' class="easyui-textbox" data-options="required:false,width:450,editable:true">
                </td>
            </tr>
            <tr>
                <td class="label" colspan="4" style="text-align: left;font-size: 20px;">
                <div id="app">
                    <div class="divider">
                        <span style="margin-left: 50px">公式绘制</span>
                    </div>
                    <draggable class="dragCon" v-model="list" :options="dragToOptions" @end="onEnd">
                        <span class="drag-li" v-for="(item, index) in list" :key="index">
                            <template v-if="item.type === 'const'">
                                <input type="text" class="const-input" v-model="item.value">
                            </template>
                            <template v-else>
                                {{item.text}}
                            </template>
                            <a href="javascript:void()" @click="del(index)">X</a>
                        </span>
                    </draggable>
                    <ul class="compute-list">
                        <draggable v-model="computeSign" :options="dragOptions" @end="onEnd">
                            <li v-for="(item, index) in computeSign" :key="index">{{item.text}}</li>
                        </draggable>
                        <draggable v-model="fields" :options="dragOptions1" @end="onEnd">
                            <li v-for="(item, index) in fields" :key="index">{{item.text}}</li>
                        </draggable>
                        <draggable v-model="constant" :options="dragOptions2" @end="onEnd">
                            <li v-for="(item, index) in constant" :key="index">{{item.text}}</li>
                        </draggable>
                    </ul>
                    <button type="button" class="build-btn" @click="build">生成表达式</button>
                    </div>
                </td>
            </tr>
	        <tr>
                <td class="label"></td>
                <td >
                    <!-- <input id='pc_pid' class="easyui-textbox" data-options="required:false,width:150,editable:true" > -->
                </td>
                <td class="label"></td>
                <td style="text-align:right">
                    <a onclick='save()' class="button button-primary button-rounded button-small"                        
                    ><i class="fa fa-check"></i>保存</a>
                    <!-- <input id='partsName' class="easyui-textbox" data-options="required:false,width:150,editable:true"  >        -->
                </td>
            </tr>	                   
	    </table>
	</div>
	<!-- <div data-options="region:'south',iconCls:'icon-reload',title:'',split:false,border:true" style="height: 45px;border-width:0px">  
        <div style="text-align: right;margin-top: 5px">
            <a onclick='save()' class="button button-primary button-rounded button-small"><i class="fa fa-check"></i>保存</a>
        </div>        
    </div> -->
</body> 
</html>
<script type="text/javascript">
 
 	$(function() {
	  $('#pc_pid').textbox('setValue',GetQueryString('uuid'));
	}); 
	
  function save() {
      var obj = new Object();
      console.info('save');
      obj.pc_pid = $('#pc_pid').textbox('getValue');  
      obj.partsName = $('#partsName').textbox('getValue');  
      obj.partsUnit = $('#partsUnit').textbox('getValue');  
      obj.partsType = $('#partsType').textbox('getValue');  
      obj.ifMatch = $('#ifMatch').textbox('getValue');
      obj.ifChoice = $('#ifChoice').combobox('getText'); 
      $.ajax({
          url: "/extensionModel/save", 
          type: "POST",
          dataType: 'json',
          data: {
              'data': JSON.stringify(obj)
          },
          error: function() //失败
          {
//             shuoheUtil.layerTopMaskOff();
//             shuoheUtil.layerTopMsgError('远程通信失败');
          },
          success: function(data) //成功
          {
              shuoheUtil.layerTopMaskOff();
              if (data.result == true) {
                  var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引          
                  parent.layer.close(index); //再执行关闭
                  parent.parent.$('#dg').datagrid('reload');
                  shuoheUtil.layerMsgSaveOK('保存成功');
              } else {
                  shuoheUtil.layerTopMsgError(data.describe);
              }
          }
      });
  }
</script>
<script>
var vm = new Vue({
    el: '#app',
    data () {
        return {
            computeSign: [
                {
                    type: 'computeSign',
                    text: '+',
                    value: '+'
                },
                {
                    type: 'computeSign',
                    text: '-',
                    value: '-'
                },
                {
                    type: 'computeSign',
                    text: '*',
                    value: '*'
                },
                {
                    type: 'computeSign',
                    text: '/',
                    value: '/'
                },
                {
                    type: 'computeSign',
                    text: '(',
                    value: '('
                },
                {
                    type: 'computeSign',
                    text: ')',
                    value: ')'
                }
            ],
            fields: [
                {
                    type: 'field',
                    text: '单价',
                    value: 'price'
                },
                {
                    type: 'field',
                    text: '数量',
                    value: 'num'
                }
            ],
            constant: [
                {
                    type: 'const',
                    text: '常量',
                    value: '0'
                }
            ],
            list: [],
            equation: '',
            equation1: '',
            result: ''
        }
    },
    methods: {
        init: function () { // vue初始化
            
        },
        onEnd: function (e) {
            if (e.clone !== null) {
                if (e.clone.innerText === '常量') {
                    this.list.splice(this.list.length - 1, 1, JSON.parse(JSON.stringify(this.constant[0])))
                }
            }
        },
        del: function (index) {
            this.list.splice(index, 1)
        },
        build: function () {
            this.equation = ''
                this.equation1 = ''
            for (let iterator of this.list) {
                if (iterator.type == 'field') {
                    this.equation += iterator.text
                    this.equation1 += iterator.value
                } else {
                    this.equation += iterator.value
                    this.equation1 += iterator.value
                }
            }
            
            buildInput(this.equation, JSON.stringify(this.list), this.equation1)
        }
    },
    computed: {
    dragOptions () { // 拖拽源配置
        return {
        group: {
            name: 'controlTo',
            pull: 'clone'
        },
        sort: false
        }
        },
        dragOptions1 () { // 拖拽源配置
        return {
        group: {
            name: 'controlTo1',
                    pull: 'clone'
        },
        sort: false
        }
    },
        dragOptions2 () { // 拖拽源配置
        return {
        group: {
            name: 'controlTo2',
                    pull: 'clone'
        },
        sort: false
        }
    },
    dragToOptions () { // 拖拽目标配置
        return {
        group: {
                    put: ['controlTo', 'controlTo1', 'controlTo2']
        }
        }
    }
    },
    mounted () {
        this.init()
    }
})
$(function(){
    $.ajax({
        url: "/productCategory/getFanParameterByPcPId", 
        type: "POST",
        dataType: 'json',
        data: {
            'pcPId': fanTypeId
        },
        error: function() //失败
        {
            // shuoheUtil.layerTopMaskOff();
            // shuoheUtil.layerTopMsgError('远程通信失败');
        },
        success: function(data)//成功
        {
            console.log(data)
                var tem = []
            for (const key in data) {
              if (data.hasOwnProperty(key)) {
                tem.push({type: 'field', text: key, value: data[key]})
              }
            }
            vm.$data.fields = tem
        }
    });
})
function buildInput(val, str, equation){
    $('#design_formulas').textbox('setValue', val);
    $('#designJson').val(str);
    console.log(equation);
    console.log(Math.express(equation));
    $('#dosage').textbox('setValue', Math.express(equation));
}
Math.express = (function() {
    
    function express(expression) {
        return cc(c2a(expression));
    }

    // 两个浮点数求和
    express.add = function(a, b) {
        var r1, r2, m;
        try {
            r1 = a.toString().split('.')[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = b.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return Math.round(a * m + b * m) / m;
    }

    // 两个浮点数相减
    express.sub = function(a, b) {
        var r1, r2, m;
        try {
            r1 = a.toString().split('.')[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = b.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        n = (r1 >= r2) ? r1 : r2;
        return (Math.round(a * m - b * m) / m).toFixed(n);
    }

    // 两数相除
    express.div = function(a, b) {
        var t1, t2, r1, r2;
        try {
            t1 = a.toString().split('.')[1].length;
        } catch (e) {
            t1 = 0;
        }
        try {
            t2 = b.toString().split(".")[1].length;
        } catch (e) {
            t2 = 0;
        }
        r1 = Number(a.toString().replace(".", ""));
        r2 = Number(b.toString().replace(".", ""));
        return (r1 / r2) * Math.pow(10, t2 - t1);
    }

    express.mul = function(a, b) {
        var m = 0, s1 = a.toString(), s2 = b.toString();
        try {
            m += s1.split(".")[1].length
        } catch (e) {
        }
        try {
            m += s2.split(".")[1].length
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    }

    // 运算符优先级
    var priority = express.priority = {
        "+" : 1,
        "-" : 1,
        "*" : 9,
        "/" : 9,
        "%" : 9
    };

    var cal = {
        "+" : function(a, b) {
            return express.add(a, b);
        },
        "-" : function(a, b) {
            return express.sub(a, b);
        },
        "*" : function(a, b) {
            return express.mul(a, b);
        },
        "/" : function(a, b) {
            return express.div(a, b);
        }
    };

    // 中缀表达式转后缀表达式
    function c2a(exp) {
        exp = exp.replace(/\s+/g, "").match(/[1-9]\d{0,}(?:\.\d+)?|[\+\-\*\/\%\(\)]/g);
        var stack = [], result = [];
        stack.peek = function() {
            return this[this.length - 1];// 弹出但不删除
        }

        for (var i = 0; i < exp.length; i++) {
            var v = exp[i];
            if (/[1-9]\d{0,}(?:\.\d+)?/.test(v)) {
                // 1.遇到操作数：直接输出（添加到后缀表达式中)
                result.push(v);
            } else if (stack.length === 0) {
                // 2.栈为空时，遇到运算符，直接入栈
                stack.push(v);
            } else if (v == "(") {
                // 3.遇到左括号：将其入栈
                stack.push(v);
            } else if (v == ")") {
                // 4.遇到右括号：执行出栈操作，并将出栈的元素输出，直到弹出栈的是左括号，左括号不输出。
                while (stack.peek() !== "(") {
                    result.push(stack.peek())
                    stack.pop();
                    if (stack.length === 0) {
                        return new Error("error expression"); // 缺少左括号
                    }
                }
                stack.pop();
            } else if (/[\+\-\*\/\%]/.test(v)) {
                // 5.遇到其他运算符：加减乘除：弹出所有优先级大于或者等于该运算符的栈顶元素，然后将该运算符入栈
                while (priority[v] <= priority[stack.peek()]) {
                    result.push(stack.peek())
                    stack.pop();
                }
                stack.push(v);
            }
        }
        // 6.最终将栈中的元素依次出栈，输出。
        while (stack.length > 0) {
            if (stack.peek() === '(') {
                return new Error("error expression"); // 缺少右括号
            }
            result.push(stack.pop())
        }

        return result;
    }

    // 计算结果
    function cc(queue) {
        var v, a, b, stack = [];
        while (queue.length > 0) {
            var v = queue.shift();
            if (/[1-9]\d{0,}(?:\.\d+)?/.test(v)) {
                stack.push(v)
            } else {
                b = stack.pop();
                a = stack.pop();
                stack.push(cal[v](a, b));
            }
        }
        if (stack.length === 1) {
            return stack.pop();
        }

        return null;
    }

    return express;

})();
</script>